package structuralModel.agentModel.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 2023/12/29
 * <p>
 * ZhangYi
 * Description 动态代理模式 : 实现InvocationHandler接口,重写invoke 方法
 */
public class DynamicProxy implements InvocationHandler {
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }


    /**
     * 获取代理对象
     *
     * @return {@link Object}
     */
    public Object getProxy() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),
                                      this);
    }

    @Override
    public Object invoke(Object proxy,
                         Method method,
                         Object[] args) throws Throwable {
        log(method.getName());
        Object result = method.invoke(target,
                                      args);
        return result;
    }

    private void log(String msg) {
        System.out.println("执行了: " + msg + "方法");
    }
}
